﻿using System;
using Microsoft.Office.Interop.Word;

namespace CSharpAutomation
{
    class WordAutomate 
    {
        private Application _wordApp;
        private Documents   _wordDocs;
        private Document    _activeDoc;

        #region
        private static object _missing = System.Reflection.Missing.Value;

        #endregion 
        
        /* * * * * * * * * * * * * * * * * * * * * * *
         * Luu y cac tham so truyen vao theo thu tu  *
         * tham so nao trong co the truyen vao gia   *
         * tri "void"                                *
         * * * * * * * * * * * * * * * * * * * * * * */

        // Create new App
        public void New() {
            if (_wordApp == null) {
                _wordApp = new Application();
                _wordApp.Visible = true; // Set visible cho Word 
            }
        }
        // Create App from current running apps
        public void GetApp(Object avaiApp) {
            _wordApp = (Application) avaiApp;
            _wordApp.Visible = true;
        }
        // Create new Doc
        public void NewDoc() {
            _wordApp.Documents.Add(ref _missing, ref _missing, ref _missing, ref _missing);
            _activeDoc = _wordApp.ActiveDocument;
        }
        // Get name of Active Doc
        public string GetName() {
            return _activeDoc.Name;
        }
        // Check if a document is available
        public bool HasDoc() {
            _wordDocs = _wordApp.Documents;
            if (_wordDocs.Count != 0) {
                _activeDoc = _wordApp.ActiveDocument;
                return true;
            }
            return false;
        }
        // Close document and app
        public void Close(string fileName) {
            SaveAs(fileName); // Save before close with a name of last update
            object nosave = WdSaveOptions.wdDoNotSaveChanges; // We don't need to save because we saved above
            _wordDocs.Close(ref nosave,ref _missing, ref _missing); // Close all docs without saving
            _wordApp.Quit(ref nosave,ref _missing, ref _missing); // Close App without saving 
        }
        // Do Save Document with specified fileName in parameter
        public void SaveAs(string fileName) {
            object name = fileName;
            _activeDoc.SaveAs(ref name, ref _missing, ref _missing, ref _missing, ref _missing,
                              ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing,
                              ref _missing, ref _missing, ref _missing, ref _missing, ref _missing);
        }
    }
}
